﻿using System.Collections.Generic;
using System.ComponentModel.Composition;
using Caliburn.Micro;
using DomusDotNet.Sbm.Client.SL4.Infrastructure;
using DomusDotNet.Sbm.Client.SL4.Services;
using DomusDotNet.Sbm.Client.SL4.WCFServices;
using System;

namespace DomusDotNet.Sbm.Client.SL4.ViewModels
{

    [Export]
    [PartCreationPolicy(CreationPolicy.NonShared)]
    public class LoginViewModel : Screen, IHasBusyState
    {
      
        IEventAggregator eventAggregator;
        [ImportingConstructor]
        public LoginViewModel(IEventAggregator eventAggregator)
        {
            this.eventAggregator = eventAggregator;
            ErrorMessage = string.Empty;
            BusyState = new BusyState();
        }




        string username;
        public string Username
        {
            get { return username; }
            set { username = value; ErrorMessage = string.Empty; }
        }

        string password;
        public string Password
        {
            get { return password; }
            set { password = value; ErrorMessage = string.Empty; }
        }

        public string ErrorMessage { get; set; }

        public BusyState BusyState { get; private set; }

        public bool CanLogin
        {
            get { return !string.IsNullOrWhiteSpace(Username) && !string.IsNullOrWhiteSpace(Password); }
        }

        public IEnumerable<IResult> Login()
        {

            using (BusyState.Set())
            {
                ErrorMessage = string.Empty;

                var login = CallService.For(
                    new LoginRequest { UserName = this.Username, Password = this.Password }
                );
                yield return login;

                var response = login.GetResponse<LoginResponse>();

                if (response.Result)
                {
                    eventAggregator.Publish(
                        new LoggedInEvent
                        {
                            Principal = new DefaultPrincipal(Username, new Guid(response.SessionGUID))
                        }
                    );
                }
                else
                {
                    ErrorMessage = response.Errors.GetStringMessage();
                }
            }
        }



        public static class Factory
        {
            [Export(typeof(Func<LoginViewModel>))]
            public static LoginViewModel Create() { return IoC.Get<LoginViewModel>(); }
        }
    }


}
